package gw.com.android.presenter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.gwtsz.gts2.hx.R;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.LivenessActivity;
import com.megvii.livenesslib.util.ConUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import gw.com.android.ui.WebFragment;
import gw.com.android.utils.ThreadPool;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2018-06-11.
 */
public class MegLive {

    public static void startLiveness(final Fragment fragment, final OnMegLiveListener listener) {
        Logger.i("meglive", "startLiveness");
        final Context context = fragment.getContext();
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(context);
                LivenessLicenseManager licenseManager = new LivenessLicenseManager(context);
                manager.registerLicenseManager(licenseManager);
                String uuid = ConUtil.getUUIDString(context);
                manager.takeLicenseFromNetwork(uuid);
                if (licenseManager.checkCachedLicense() > 0) {
                    //授权成功
                    Logger.i("meglive", "license succuss");
                    fragment.startActivityForResult(new Intent(context, LivenessActivity.class), WebFragment.REQUEST_CODE_MEGLIVE);
                } else {
                    //授权失败
                    Logger.i("meglive", "license failure");
                    if (listener != null) {
                        listener.onResult(false, null, null);
                    }
                }
            }
        });
    }

    public static void handleResult(Intent data, OnMegLiveListener listener) {
        Logger.i("meglive", "handleResult");
        if (data == null) {
            Logger.i("meglive", "data is null");
            notifyResult(false, null, null, listener);
            return;
        }
        Bundle bundle = data.getExtras();
        if (bundle == null) {
            Logger.i("meglive", "bundle is null");
            notifyResult(false, null, null, listener);
            return;
        }
        String result = bundle.getString("result");
        if (TextUtils.isEmpty(result)) {
            Logger.i("meglive", "result is null");
            notifyResult(false, null, null, listener);
            return;
        }
        try {
            JSONObject json = new JSONObject(result);
            int resultcode = json.optInt("resultcode");
            boolean isSuccess = validateId(resultcode);
            if (isSuccess) {
                String delta = bundle.getString("delta");
                Map<String, byte[]> images = (Map<String, byte[]>) bundle.getSerializable("images");
                byte[] image_best = images == null ? null : images.get("image_best");
                notifyResult(true, delta, image_best, listener);
                return;
            }
        } catch (JSONException e) {
            Logger.e("meglive", e);
        }
        notifyResult(false, null, null, listener);
    }

    private static void notifyResult(boolean isSuccess, String delta, byte[] image, OnMegLiveListener listener) {
        if (listener != null) {
            listener.onResult(isSuccess, delta, image);
        }
    }

    private static boolean validateId(int resID) {
        if (resID == R.string.verify_success) {
            Logger.i("meglive", "validateId 验证成功");
            return true;
        } else if (resID == R.string.liveness_detection_failed_not_video) {
            Logger.i("meglive", "validateId 活体检测连续性检测失败");
            return false;
        } else if (resID == R.string.liveness_detection_failed_timeout) {
            Logger.i("meglive", "validateId 活体检测超时失败");
            return false;
        } else if (resID == R.string.liveness_detection_failed) {
            Logger.i("meglive", "validateId 活体检测失败");
            return false;
        }
        Logger.i("meglive", "validateId 活体检测失败 unknow...");
        return false;
    }

    public interface OnMegLiveListener {

        // code : 0 成功
        void onResult(boolean isSuccess, String delta, byte[] image);

    }

}
